package com.nd.our2project.controller;



import com.nd.our2project.pojo.LoginUser;
import com.nd.our2project.pojo.Result;
import com.nd.our2project.pojo.User;
import com.nd.our2project.service.UserService;
import com.nd.our2project.utils.ValidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;


@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("login")
    public Result login(@Validated LoginUser loginUser, BindingResult bindingResult, HttpSession session){
        if(bindingResult.hasFieldErrors()){
            return ValidUtils.valida(bindingResult);
        }
        int i = userService.queryUser(loginUser);
        if(i == 0){
            return Result.fail("邮箱或密码错误,登录失败!");
        }
        session.setAttribute("email",loginUser.getEmail());
        return Result.ok("登录成功");
    }


    @RequestMapping("register")
    public Result register(User user){
        int add = userService.addUser(user);
        if(add == 0) return Result.fail("注册失败");
        return Result.ok("注册成功");
    }

    @RequestMapping("allUsers")
    public Result allUsers(){
        List<User> userList = userService.queryAllUsers();
        return Result.ok(userList);
    }
    @RequestMapping("AaronMnmn")
    public Result AaronMnmn(){
        return Result.ok("AaronMnmn");
    }

    // 王宏亮（liang） 修改
    @RequestMapping("queryByJob")
    public Result queryById(String job){

        String email = userService.queryUserById(job);

        return Result.ok(email);
    }
    //张鹏飞（Mr.Zhang）新增
    @RequestMapping(value = "selectByEmail",method = RequestMethod.POST)
    public Result selectById(User user){
        User users= userService.selectByEmail(user.getEmail());
        return Result.ok(users);
    }

}
